﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using System.Diagnostics;

namespace SPUtility
{
    public class ListActivity
    {
         const string debug = "DEBUG";



        [Conditional(debug)]
        private void WriteToLog(string message)
        {

            SPUtility.LogHandler.LogError(SPUtility.LogType.CommonUtility,
                "[" + System.DateTime.Now.ToLongDateString() + ":T:" + System.DateTime.Now.ToLongTimeString() + ":M:" + System.DateTime.Now.Millisecond.ToString() + "] "
                + message);
        }

        public int AddItem(string siteUrl, string listName, Dictionary<string, string> fieldValueCollection)
        {
            WriteToLog(string.Format("{0}--{1}--{2}", siteUrl, listName,"THIS IS TEST 111."));
            SPSite site = null;
            SPWeb mySite = null;
            if (SPContext.Current == null)
            {
                site = new SPSite(siteUrl);
                mySite = site.OpenWeb();

            }
            else
            {
                mySite = SPContext.Current.Web;
            }
            try
            {

                mySite.AllowUnsafeUpdates = true;
                SPListItem item = mySite.Lists[listName].Items.Add();

                foreach (var fieldValue in fieldValueCollection)
                {
                    if (item.Fields.ContainsField(fieldValue.Key))
                    {
                       
                            item[fieldValue.Key] = fieldValue.Value;

                    }
                }
                item.Update();
                WriteToLog("Item created " + item.ID.ToString());
                return item.ID;
            }
            catch (Exception Ex)
            {
                LogHandler.LogError(LogType.Workflow, Ex.ToString());
            }
            finally
            {
                mySite.AllowUnsafeUpdates = false;
                if (mySite != null)
                {
                    mySite.Dispose();
                }
                if (site != null)
                {
                    site.Dispose();
                }
            }


            return 0;
        }



        public bool UpdateItem(string siteUrl, string listName,int itemID, Dictionary<string, string> fieldValueCollection)
        {
            SPSite site = null;
            SPWeb mySite = null;
            if (SPContext.Current == null)
            {
                site = new SPSite(siteUrl);
                mySite = site.OpenWeb();

            }
            else
            {
                mySite = SPContext.Current.Web;
            }
            try
            {

                
                SPListItem item = mySite.Lists[listName].Items.GetItemById(itemID);
                mySite.AllowUnsafeUpdates = true;
                foreach (var fieldValue in fieldValueCollection)
                {
                    if (item.Fields.ContainsField(fieldValue.Key))
                    {
                        item[fieldValue.Key] = fieldValue.Value;
                    }
                }
                item.Update();
                return true;
            }
            catch (Exception Ex)
            {
                LogHandler.LogError(LogType.Workflow, Ex.ToString());
            }
            finally
            {
                mySite.AllowUnsafeUpdates = false;
                if (mySite != null)
                {
                    mySite.Dispose();
                }
                if (site != null)
                {
                    site.Dispose();
                }
            }


            return false;
        }

        public bool DeleteItem(string siteUrl, string listName, int itemID, Guid taskUniqueID)
        {

            WriteToLog(string.Format("{0}--{1}--{2}--{3}",siteUrl,listName,itemID,taskUniqueID));
           // return true;
            SPSite site = null;
            SPWeb mySite = null;
            if (SPContext.Current == null)
            {
                site = new SPSite(siteUrl);
                mySite = site.OpenWeb();

            }
            else
            {
                mySite = SPContext.Current.Web;
            }
            try
            {
                SPListItem item = mySite.Lists[listName].Items.GetItemById(itemID);


                foreach (SPWorkflow wrkFlow in item.Workflows)
                {
                    Guid[] allGuid = new Guid[wrkFlow.Tasks.Count];
                    int count = 0;
                    foreach (SPWorkflowTask task in wrkFlow.Tasks)
                    {

                        SPListItem ity = ((Microsoft.SharePoint.SPListItem)(task));
                        Console.WriteLine(ity["GUID"]);
                        Guid itGuid = new Guid(ity["GUID"].ToString());
                        //if (task[SPBuiltInFieldId.TaskStatus] == null || task[SPBuiltInFieldId.TaskStatus].ToString() != "Completed")
                        WriteToLog("Searching to complete the task" + task.Title + "___" + task.ID.ToString());
                        if (!itGuid.Equals(taskUniqueID)  && !ity["Completed"].ToString().Equals("true", StringComparison.CurrentCultureIgnoreCase))
                        {
                            WriteToLog("Found to complete the task" + task.Title + "___" + task.ID.ToString());
                            task[SPBuiltInFieldId.Completed] = "TRUE";
                            task[SPBuiltInFieldId.PercentComplete] = 1;
                            task[SPBuiltInFieldId.TaskStatus] = "Completed";//SPResource.GetString(new CultureInfo((int)objWeb.Language, false), "WorkflowTaskStatusComplete", new object[0]);
                            task["Description"] = "Automated Serial Approval Completed";
                            task.SystemUpdate(false);
                        
                        }

                        
                    }

                    
                }
                WriteToLog("All task completed successfully with Task Unique ID --> SERIAL..");
               item.Delete();
                return true;
            }
            catch (Exception Ex)
            {
                LogHandler.LogError(LogType.Workflow, Ex.ToString());
            }
            finally
            {
                mySite.AllowUnsafeUpdates = false;
                if (mySite != null)
                {
                    mySite.Dispose();
                }
                if (site != null)
                {
                    site.Dispose();
                }
            }
            return false;
        }


        public bool DeleteItem(string siteUrl, string listName, int itemID)
        {
            WriteToLog(string.Format("{0}--{1}--{2}--{3}", siteUrl, listName, itemID, 123));
            SPSite site = null;
            SPWeb mySite = null;
            if (SPContext.Current == null)
            {
                site = new SPSite(siteUrl);
                mySite = site.OpenWeb();

            }
            else
            {
                mySite = SPContext.Current.Web;
            }
            try
            {
                SPListItem item = mySite.Lists[listName].Items.GetItemById(itemID);


                foreach (SPWorkflow wrkFlow in item.Workflows)
                {
                    Guid[] allGuid = new Guid[wrkFlow.Tasks.Count];
                    int count = 0;
                    foreach (SPWorkflowTask task in wrkFlow.Tasks)
                    {
                      
                        if (task[SPBuiltInFieldId.TaskStatus] == null || task[SPBuiltInFieldId.TaskStatus].ToString() != "Completed")
                        {
                            allGuid[count] = task.UniqueId;
                            count++;
                            task[SPBuiltInFieldId.Completed] = "TRUE";
                            task[SPBuiltInFieldId.PercentComplete] = 1;
                            task[SPBuiltInFieldId.TaskStatus] = "Completed";//SPResource.GetString(new CultureInfo((int)objWeb.Language, false), "WorkflowTaskStatusComplete", new object[0]);
                            task["Description"] = "Automated Serial Approval Completed";
                           // task.SystemUpdate(false);
                            //task.Delete();
                            
                        //    break;
                        }
                    }

                  
                }
                WriteToLog("All task completed successfully ... PARALLEL..");
                item.Delete();
                return true;
            }
            catch (Exception Ex)
            {
                LogHandler.LogError(LogType.Workflow, Ex.ToString());
            }
            finally
            {
                mySite.AllowUnsafeUpdates = false;
                if (mySite != null)
                {
                    mySite.Dispose();
                }
                if (site != null)
                {
                    site.Dispose();
                }
            }
            return false;
        }



    }
}
